<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Mindex extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
    }
	
	public function getProject(){
		if( $this->session->userdata('level') == 1 ){
			$data = $this->db->query('SELECT p.*,u.fullname,u.username FROM project AS p INNER JOIN user AS u ON u.id = p.user_id WHERE p.active=1 ORDER BY p.is_pin DESC, p.created DESC ')->result_object();
		}else{
			if( $this->session->userdata('level') == 2 ){
				$data = $this->db->query('SELECT p.*,u.fullname,u.username FROM project AS p INNER JOIN user AS u ON u.id = p.user_id INNER JOIN project_key AS pk ON pk.project_id = p.id WHERE p.active = 1 AND pk.user_id = '.$this->session->userdata('admin_id').' ORDER BY p.is_pin DESC, p.created DESC ')->result_object();
			}
		}
		foreach ($data AS $el=>$le){
			if( !in_array($le->time_start,array('',null)) && !in_array($le->time_end,array('',null)) ){
				$le->time_percent = ceil((time() - strtotime($le->time_start))/(strtotime($le->time_end) - strtotime($le->time_start))*100);
				if( $le->time_percent >= 100 ){
					$le->time_percent = 100;
				}
			}else{
				$le->time_percent = 0;
			}
			$user = $this->db->query('SELECT u.id,u.username,u.fullname FROM user AS u INNER JOIN project_key AS pk ON u.id = pk.user_id WHERE pk.project_id =  '.$le->id.' ')->result_object();
			$le->user = $user;
			$total_rate = $this->db->query('SELECT SUM(rate) AS rate FROM module_key WHERE project_id = '.$le->id.' ')->row_object()->rate;
			$num_rate = $this->db->query('SELECT id FROM module_key WHERE project_id = '.$le->id.' ')->num_rows();
			$le->percent = ceil($total_rate/$num_rate);
			
			$user_rate = $this->db->query('SELECT DISTINCT mk.user_id as user_id, u.display_name as fullname FROM module_key as mk inner join user as u on u.id = mk.user_id WHERE mk.project_id = '.$le->id.' ')->result_object();
			foreach ( $user_rate AS $el2=>$le2 ){
				$total_rate2 = $this->db->query('SELECT SUM(rate) AS rate FROM module_key WHERE project_id = '.$le->id.' AND user_id = '.$le2->user_id.' ')->row_object()->rate;
				$number2 = $this->db->query('SELECT id FROM module_key WHERE project_id = '.$le->id.' AND user_id = '.$le2->user_id.' ')->num_rows();
				$user_rate[$el2]->rate2 = ceil($total_rate2/$number2);
			}
			$le->user_rate = $user_rate;
		}
		//echo '<pre>';die(print_r($data));
		return $data;
	}
	
}
